/*
 * author:陈偲
 * update:20150805
 *  desc:
 *      1.给Date增加AddDate函数
 */

Array.prototype.indexOf = function (c) {
    for (var i = 0; i < this.length; i++)
        if (this[i] == c) return i;
    return -1;
};
String.prototype.Trim = function () { //清除前端后后端的空格
    return $.trim(this);
    //	return this.replace(/(^[\s|&nbsp;]+)|([\s|&nbsp;]+$)/g, "");
};
String.prototype.TrimStart = function () {
    return this.replace(/(^\s+)/g, "");
};
String.prototype.TrimEnd = function () {
    return this.replace(/(\s*$)/g, "");
};
String.prototype.IsPhone = function () {
    var regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

    return regPhone.test(this);
};
String.prototype.HTMLEnCode = function () { //把手写的HTML编码转换成实体编码模式
    var s = this.replace(/(^\s*)|(\s*$)/g, "");
    s = s.replace(/&/g, "&gt;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    //s = s.replace(/    /g, "&nbsp;");
    s = s.replace(/\'/g, "'");
    s = s.replace(/\"/g, "&quot;");
    //s = s.replace(/\n/g, "<br>");   
    return s;
};
String.prototype.HTMLDeCode = function () { //把实体编码模式的HTML编码转换成普通结果模式
    var s = this.replace(/(^\s*)|(\s*$)/g, "");
    s = s.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, "    ");
    s = s.replace(/'/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    //s = s.replace(/<br>/g, "\n");
    s = s.replace(/&#39;/g, "\'");
    return s;
};
String.prototype.ReplaceBRToEnter = function () {
    ///	<summary>
    ///		替换字符串中所有的<br/>、<br />、<br>成\r\n
    ///	</summary>
    ///	<returns type="String">替换后的结果</returns>

    return this.replace(/<br\/>/ig, "\r\n")
        .replace(/<br \/>/ig, "\r\n")
        .replace(/<br>/ig, "\r\n");
};
String.prototype.ClearByEnter = function () {
    ///	<summary>
    ///		替换字符串中所有的换行和回车
    ///	</summary>
    ///	<returns type="String">替换后的结果</returns>

    return this.replace(/\r\n/ig, "<br/>")
        .replace(/\n/ig, "<br/>")
        .replace(/\r/ig, "<br/>");
};
String.prototype.Len = function () { //计算字符串长度，区分中英文（中文2个字符）。
    var c = this.match(/[^\x00-\xff]/ig);
    return parseInt(this.length + parseInt(c == null ? 0 : c.length));
};
String.prototype.ReplaceTemplate = function (key, recnt) {
    ///	<summary>
    ///		替换模板中的内容，模板必须用$开头和$结束！
    ///	</summary>
    ///	<param name="key" type="String">
    ///		模板中的值
    /// </param>
    ///	<param name="recnt" type="String">
    ///		模板中待替换的值
    /// </param>
    ///	<returns type="String">替换后的结果</returns>

    var content = this;
    var tkey = "content.replace(/\\{\\$" + key + "\\$\\}/g,'" + recnt + "')";
    var tkey2 = "content.replace(/\\%7B\\$" + key + "\\$\\%7D/g,'" + recnt + "')";
    try {
        content = eval(tkey);
    } catch (e) {
        //confirm(tkey);
        tkey = "content.replace(/\\{\\$" + key + "\\$\\}/g,' ')";
        content = eval(tkey);
    }
    try {
        content = eval(tkey2);
    } catch (e) {
        //confirm(tkey2);
        tkey2 = "content.replace(/\\%7B\\$" + key + "\\$\\%7D/g,'')";
        content = eval(tkey2);
    }
    return content;
};
String.prototype.FormatString = function () {
    ///	<summary>
    ///		格式化字符串
    ///	</summary>
    ///	<returns type="String">替换后的字符串</returns>

    return this.replace(/\\/g, "\\\\").replace(/'/g, "\\\'");
};

String.prototype.StringToJsonObject = function () { //把字符串转换为对象
    //		if (json == null || json == undefined || json == "") {
    //			return "";
    //		}
    return eval("(" + this + ")");
}

Date.prototype.pattern = function (fmt) {
    /**     
     * 对Date的扩展，将 Date 转化为指定格式的String
     * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
     * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
     * eg:
     * (new Date()).pattern("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
     * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
     * (new Date()).pattern("yyyy-MM-dd EE HH:mm:ss") ==> 2009-03-10 周二 08:09:04
     * (new Date()).pattern("yyyy-MM-dd EEE HH:mm:ss") ==> 2009-03-10 星期二 08:09:04
     * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
     */

    var o = {
        "M+": this.getMonth() + 1, //月份        
        "d+": this.getDate(), //日        
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时        
        "H+": this.getHours(), //小时        
        "m+": this.getMinutes(), //分        
        "s+": this.getSeconds(), //秒        
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度        
        "S": this.getMilliseconds() //毫秒        
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
};
String.prototype.pattern = function (fmt) {
    ///	<summary>
    ///		格式化取得的时间
    ///	</summary>
    ///	<param name="fmt" type="String">
    ///		时间格式化命令  
    ///	* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符     
    ///	* 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)     
    ///	* eg:     
    ///	* String.pattern("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423     
    ///	* String.pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04     
    ///	* String.pattern("yyyy-MM-dd EE HH:mm:ss") ==> 2009-03-10 周二 08:09:04     
    ///	* String.pattern("yyyy-MM-dd EEE HH:mm:ss") ==> 2009-03-10 星期二 08:09:04     
    ///	* String.pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18     
    ///	*/
    /// </param>
    ///	<returns type="String">替换后的结果</returns>

    var date;
    if (this.indexOf("Date") != -1) {
        date = eval("new " + this.substring(1, this.length - 1));
    } else if ((new Date(this)).getTime()) {
        date = new Date(this);
    } else {
        date = new Date(this.replace(/-/ig, "/"));
    }

    return date.pattern(fmt);
};
Date.prototype.AddDate = function (hour, minute, second, day) {
    ///	<summary>
    ///		加上指定时分秒日后的时间
    ///	</summary>
    ///	<param name="hour" type="Number">
    ///		待增加的小时数,没有则为0  
    /// </param>
    ///	<param name="minute" type="Number">
    ///		待增加的分钟数,没有则为0  
    /// </param>
    ///	<param name="second" type="Number">
    ///		待增加的秒数,没有则为0  
    /// </param>
    ///	<param name="day" type="Number">
    ///		待增加的天数,没有则为0  
    /// </param>
    ///	<returns type="String">替换后的结果</returns>

    var temp = 1000;
    var tempSecond = 0;
    var tempMinute = 0;
    var tempHour = 0;
    var tempDay = 0;

    if (second) {
        tempSecond = temp * second;
    }
    if (minute) {
        tempMinute = temp * 60 * minute;
    }
    if (hour) {
        tempHour = temp * 60 * 60 * hour;
    }
    if (day) {
        tempDay = temp * 60 * 60 * 24 * day;
    }

    var date = this.getTime() + tempSecond + tempMinute + tempHour + tempDay;

    return date;
};

function getMousePoint(ev) { //获取当前的鼠标位置
    var x = y = 0;

    if (!ev) {
        ev = window.event;
    }

    if (typeof window.pageYoffset != 'undefined') { //pageYoffset是Netscape特有
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { //检测标准模式
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    } else if (typeof document.body != 'undefined') {
        x = document.body.scrollLeft - document.body.clientLeft;
        y = document.body.scrollTop - document.body.clientTop;
    }

    x += ev.clientX;
    y += ev.clientY;

    return {
        'x': x,
        'y': y
    };
}

function getBrowserDimensions() { //获取当前浏览器的大小
    var winWidth = winHeight = 0;

    //获取窗口宽度
    if (window.innerWidth)
        winWidth = window.innerWidth;
    else if ((document.body) && (document.body.clientWidth))
        winWidth = document.body.clientWidth;
    //获取窗口高度
    if (window.innerHeight)
        winHeight = window.innerHeight;
    else if ((document.body) && (document.body.clientHeight))
        winHeight = document.body.clientHeight;
    //通过深入Document内部对body进行检测，获取窗口大小
    if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
        winHeight = document.documentElement.clientHeight;
        winWidth = document.documentElement.clientWidth;
    }

    return {
        'width': winWidth,
        'height': winHeight
    };
}

function isNullOrUndefined(str) {
    if (!str) {
        str = "-";
    }
    return str;
}

function appendSelect(url_or_data, sel_id, value, name, sel_value) {
    ///	<summary>
    ///		为select控件添加选项
    ///	</summary>
    ///	<param name="url_or_data" type="String">
    /// url_or_data
    /// </param>
    ///	<param name="sel_id" type="String">
    /// select控件id
    /// </param>
    ///	<param name="value" type="String">
    /// 表示value的字段
    /// </param>
    ///	<param name="name" type="String">
    /// 要显示的字段
    /// </param>
    ///	<param name="sel_value" type="String">
    /// 要选择的值（value），没有则为null
    /// </param>

    var data;

    if (url_or_data instanceof Object) {
        data = url_or_data;
    } else {
        data = Common.AjaxGetData(url_or_data);
    }

    if (data) {
        var html;

        for (var i in data) {
            var option = new Option(data[i][name], data[i][value]);
            if (data[i][value] == sel_value) {
                option.selected = true;
            }

            document.getElementById(sel_id).add(option);
        }
    }
}

/**
 * 自动滚动到文本需要显示的位置
 * author:陈偲
 * time:20170104
 */
function textControlNeedView() {
    $(document.body).delegate('input,textarea', 'focus', function () {
        var target = this;
        setTimeout(function () {
            target.scrollIntoViewIfNeeded();
            console.log('scrollIntoViewIfNeeded');
        }, 400);
    });
}

window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function ( /* function */ callback, /* DOMElement */ element) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

/**
 * 添加css文件
 */
window.addCssFile = function (cssUrl) {
    var isLoad = 0;

    var $links = $('link[type="text/css"]').each(function () {
        var $tempItem = $(this);

        if ($tempItem.attr('href').indexOf(cssUrl) === -1) {
            isLoad = 1;

            return false;
        }
    });;

    if (isLoad) {
        $("head").append("<link>");
        var css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: cssUrl
        });
    }
};

//公共方法对象
var Common = {
    GetAjax: function (type, url, data, success, errFunc, completeFunc) {
        (function () {
            if (URL) {
                if (URL.action && URL.action == 2) {
                    data = null;
                    type = 'GET';
                }
            }
        })();

        var val = "";

        var param = {
            url: url,
            //		    url: encodeURI(url),
            type: type,
            timeout: 50000,
            async: false,
            data: data,
            dataType: "json",
            success: function (tempData) { },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errFunc) {
                    errFunc(XMLHttpRequest, textStatus, errorThrown);
                }

                console.log(arguments);
            },
            complete: completeFunc
        };

        if (!success) {
            param.async = false;
            param.success = function (tempData) {
                val = tempData;
            };
        } else {
            param.async = true;
            param.success = function (r) {
                if (success) {
                    success(r);
                }
            };
        }

        $.ajax(param);

        return val;
    },
    AjaxGetData: function (url, data, success, errFunc, completeFunc) {
        ///	<summary>
        ///		Ajax的GET方法
        ///	</summary>
        ///	<param name="url" type="String">
        ///		网址/参数
        /// </param>
        ///	<param name="data" type="JSON类型">
        ///		参数
        /// </param>
        ///	<param name="success" type="Function">
        ///		回调函数，不用这个的时候为同步，用的时候为异步（有一个返回数据参数（数据））
        /// </param>
        ///	<returns type="string">同步时返回数据，异步时在回调函数中取</returns>

        return this.GetAjax('GET', url, data, success, errFunc, completeFunc);
    },
    AjaxPostData: function (url, data, success, errFunc, completeFunc) {
        ///	<summary>
        ///		Ajax的POST方法
        ///	</summary>
        ///	<param name="url" type="String">
        ///		网址/参数
        /// </param>
        ///	<param name="data" type="JSON类型">
        ///		参数
        /// </param>
        ///	<param name="success" type="Function">
        ///		回调函数，不用这个的时候为同步，用的时候为异步（有一个返回数据参数（数据））
        /// </param>
        ///	<returns type="string">同步时返回数据，异步时在回调函数中取</returns>

        return this.GetAjax('POST', url, data, success, errFunc, completeFunc);
    },

    Clone: function (obj) {
        var objClone;
        if (obj.constructor == Object) {
            objClone = new obj.constructor();
        } else {
            objClone = new obj.constructor(obj.valueOf());
        }
        for (var key in obj) {
            if (objClone[key] != obj[key]) {
                if (typeof (obj[key]) == "object") {
                    objClone[key] = arguments.callee(obj[key]);
                } else {
                    objClone[key] = obj[key];
                }
            }
        }
        objClone.toString = obj.toString;
        objClone.valueOf = obj.valueOf;
        return objClone;
    },
    //数字小写转大写
    intToChinese: function (str) {
        str = str + '';
        var len = str.length - 1;
        var idxs = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿'];
        var num = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        return str.replace(/([1-9]|0+)/g, function ($, $1, idx, full) {
            var pos = 0;
            if ($1[0] != '0') {
                pos = len - idx;
                if (idx == 0 && $1[0] == 1 && idxs[len - idx] == '十') {
                    return idxs[len - idx];
                }
                return num[$1[0]] + idxs[len - idx];
            } else {
                var left = len - idx;
                var right = len - idx + $1.length;
                if (Math.floor(right / 4) - Math.floor(left / 4) > 0) {
                    pos = left - left % 4;
                }
                if (pos) {
                    return idxs[pos] + num[$1[0]];
                } else if (idx + $1.length >= len) {
                    return '';
                } else {
                    return num[$1[0]]
                }
            }
        });
    },

    ReproduceArray: function (array, blank, id, parnetID, name) {
        ///	<summary>
        ///		重制数组：对有父节点的数组进行重制，一级加一个blank（不会改变原数组）
        ///	</summary>
        ///	<param name="array" type="Array">
        ///		传入的数组
        /// </param>
        ///	<param name="blank" type="String">
        ///		间隔符号
        /// </param>
        ///	<param name="id" type="String">
        ///		传入数组中ID的名字
        /// </param>
        ///	<param name="parnetID" type="String">
        ///		传入数组中父ID的名字
        /// </param>
        ///	<param name="name" type="String">
        ///		传入数组中要变换的属性的名字
        /// </param>
        ///	<returns type="Array">重制后的数组</returns>

        var cloneArray = Common.Clone(array);
        var arr = new Array();

        for (var i = 0; i < cloneArray.length; i++) {
            var t_parentID = null;

            if (cloneArray[i][parnetID] == "") {

                arr.push(cloneArray[i]);
                t_parentID = cloneArray[i][id];

                function childLoad(tempArray, tempParentID, tempLen, blank) {
                    for (var i = 0; i < tempArray.length; i++) {
                        if (tempArray[i][parnetID] == tempParentID) {
                            var spa = "";
                            for (var j = 0; j < tempLen; j++) {
                                spa += blank;
                            }
                            for (var att in tempArray[i]) {
                                if (att == name) {
                                    tempArray[i][att] = spa + tempArray[i][name];
                                    break;
                                }
                            }

                            arr.push(tempArray[i]);

                            var childID = tempArray[i][id];
                            var cloneLen = tempLen;

                            arguments.callee(tempArray, childID, ++cloneLen, blank);
                        }
                    }
                }

                childLoad(cloneArray, t_parentID, 1, blank);
            }
        }

        return arr;
    },
    TypeOfBrowser: {
        ///	<summary>
        ///		判断浏览器
        ///	</summary>

        IsIpad: navigator.userAgent.toLowerCase().match(/ipad/i) == "ipad",
        IsIphoneOs: navigator.userAgent.toLowerCase().match(/iphone os/i) == "iphone os",
        IsMidp: navigator.userAgent.toLowerCase().match(/midp/i) == "midp",
        IsUc7: navigator.userAgent.toLowerCase().match(/rv:1.2.3.4/i) == "rv:1.2.3.4",
        IsUc: navigator.userAgent.toLowerCase().match(/ucweb/i) == "ucweb",
        IsAndroid: navigator.userAgent.toLowerCase().match(/android/i) == "android",
        IsCE: navigator.userAgent.match(/windows ce/i) == "windows ce",
        IsWM: navigator.userAgent.toLowerCase().match(/windows mobile/i) == "windows mobile",
        IsIELow: !+[1,]
    },
    IsParentBelongElement: function (identityOrElement, parentIdentity) {
        ///	<summary>
        ///		判断指定元素是否属于某个父元素
        ///	</summary>
        ///	<param name="identityOrElement" type="String">
        ///		指定元素标识或元素
        /// </param>
        ///	<param name="parentIdentity" type="String">
        ///		父元素标识
        /// </param>
        ///	<returns type="Boolean">JQuery对象,通过length判断</returns>

        var result = $();

        if (!identityOrElement.attr) {
            identityOrElement = $(identityOrElement);
        }

        if (!identityOrElement.is(parentIdentity)) {
            identityOrElement = identityOrElement.parents(parentIdentity);
        }

        if (identityOrElement.length) {
            result = identityOrElement;
        }

        return result;
    },
    MouseMoveChangeColor: function (options) {
        ///	<summary>
        ///		鼠标移动变色
        ///	</summary>
        ///	<param name="options" type="Object">
        ///		包含元素
        ///			targetObj:目标元素
        ///			bgColor(可选):改变色彩
        /// </param>

        var settings = $.extend({
            //targetObj: targetObj,
            //changeColorObj: targetObj,
            bgColor: "#F7F7F7"
        }, options);

        $(settings.targetObj).mouseover(function () {
            $(settings.changeColorObj).css("background", settings.bgColor);
        }).mouseout(function () {
            $(settings.changeColorObj).css("background", "");
        });
    },
    DeleteObjForBase: function (obj) {
        ///	<summary>
        ///		用JavaScript删除元素
        ///	</summary>
        ///	<param name="obj" type="String Or Object">
        ///		元素标识(id或实体,必须是单个)
        /// </param>

        var child = $(obj);
        if (child.length === 1) {
            var father = child.parent();

            father.get(0).removeChild(child.get(0));
        }
    },
    /*
     * 智能机浏览器版本信息:
     */
    Browser: {
        Versions: function () {
            var u = navigator.userAgent,
                app = navigator.appVersion,
                p = navigator.platform;
            return { //移动终端浏览器版本信息 
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.toLowerCase().indexOf('micromessenger') > -1, //是微信浏览器
                win: p.indexOf("Win") == 0, //是pc
                mac: p.indexOf("Mac") == 0 //是手机
            };
        },
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    },
    //验证控件的value
    //author:陈偲
    //time:20160701
    verificationControlVal: function ($objIdsArr, confirmFunc) {

        var result = 0;

        function remind($obj, errTxt) {
            Common.toast(errTxt, 2345);

            result = 1;

            //			var top = $obj.offset().top;
            //			$(document).scrollTop(top);
        }

        var confirmF = confirmFunc || remind;

        for (var i = 0; i < $objIdsArr.length; i++) {
            var $obj = $($objIdsArr[i]);

            if ($obj.length) {
                var val = $obj.attr('data-val-require') || $obj.val().Trim() || $obj.text();
                var valFunc = $obj.attr('data-val-func');
                var valLenMax = $obj.attr('data-val-length-max');
                var valRegex = $obj.attr('data-val-regex-pattern');
                var valMin = $obj.attr('data-val-min');
                var valMax = $obj.attr('data-val-max');

                var errTxt = '您填写的有错误!';

                if (!val) {
                    confirmF($obj, $obj.attr('data-val-required'));

                    break;
                } else if (valMin && Number(valMin) > val.length) {
                    confirmF($obj, $obj.attr('data-val-min-required'));

                    break;
                } else if (valMax && Number(valMax) < val.length) {
                    confirmF($obj, $obj.attr('data-val-max-required'));

                    break;
                } else if (valRegex && (!((new RegExp(valRegex, 'g')).test(val)))) {
                    errTxt = $obj.attr('data-val-regex-require') || errTxt;

                    confirmF($obj, errTxt);

                    break;
                } else if (valFunc) {
                    var msg = Common[valFunc](val);

                    if (msg) {
                        confirmF($obj, $obj.attr('data-val-func-require') || msg);

                        break;
                    }
                } else if (valLenMax &&
                    (val.length > Number(valLenMax))) {
                    errTxt = $obj.attr('data-val-length') || errTxt;

                    confirmF($obj, errTxt);

                    break;
                }
            }
        }

        return result;
    },
    /*
     * 身份证15位编码规则：dddddd yymmdd xx p
     * dddddd：6位地区编码
     * yymmdd: 出生年(两位年)月日，如：910215
     * xx: 顺序编码，系统产生，无法确定
     * p: 性别，奇数为男，偶数为女
     *
     * 身份证18位编码规则：dddddd yyyymmdd xxx y
     * dddddd：6位地区编码
     * yyyymmdd: 出生年(四位年)月日，如：19910215
     * xxx：顺序编码，系统产生，无法确定，奇数为男，偶数为女
     * y: 校验码，该位数值可通过前17位计算获得
     *
     * 前17位号码加权因子为 Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]
     * 验证位 Y = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ]
     * 如果验证码恰好是10，为了保证身份证是十八位，那么第十八位将用X来代替
     * 校验位计算公式：Y_P = mod( ∑(Ai×Wi),11 )
     * i为身份证号码1...17 位; Y_P为校验码Y所在校验码数组位置
     */
    validateIdCard: function (idCard) {
        var result = '';

        //15位和18位身份证号码的正则表达式
        var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;

        //如果通过该验证，说明身份证格式正确，但准确性还需计算
        if (regIdCard.test(idCard)) {
            if (idCard.length == 18) {
                var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //将前17位加权因子保存在数组里
                var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
                var idCardWiSum = 0; //用来保存前17位各自乖以加权因子后的总和
                for (var i = 0; i < 17; i++) {
                    idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
                }

                var idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置
                var idCardLast = idCard.substring(17); //得到最后一位身份证号码

                //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
                if (idCardMod == 2) {
                    if (idCardLast == "X" || idCardLast == "x") {
                        //alert("恭喜通过验证啦！");
                    } else {
                        result = '身份证号码错误';
                    }
                } else {
                    //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                    if (idCardLast == idCardY[idCardMod]) {
                        //alert("恭喜通过验证啦！");
                    } else {
                        result = '身份证号码错误';
                    }
                }
            }
        } else {
            result = '身份证格式不正确';
        }

        return result;
    },
    /**
     * 验证输入框中是否有emoji表情
     */
    validateEmoji: function (txt) {
        var result;
        var reg = /\ud83c[^\udf00-\udfff]|\ud83d[^\udc00-\ude4f]|\ud83d[^\ude80-\udeff]/;

        if (reg.test(txt)) {
            result = '你输入的字符中包含emoji表情';
        }

        return result;
    },
    toast: function (b, c) {
        $('.toast').remove();

        var e = $('<div class="toast">' + b + "</div>").appendTo(document.body).show();
        var marginLeft = -e.outerWidth() / 2;

        e.addClass('toast-in').css({ 'margin-left': marginLeft + 'px', height: 'auto' }).show();

        setTimeout(function () {
            e.removeClass('toast-in').addClass('toast-out');
            setTimeout(function () {
                e.remove();
            }, .815);
        }, c);
    },
    preloader: {
        show: function (txt) {
            var defaultTxt = '加载中';

            txt = txt || defaultTxt;

            var $modal = $('.modal'),
                $modalOverlay = $('.modal-overlay');

            $modal.find('.modal-title').text(txt);

            $modal.fadeIn(300).addClass('modal-in');
            $modalOverlay.fadeIn(300).addClass('modal-overlay-visible');
        },
        hide: function () {
            var $modal = $('.modal'),
                $modalOverlay = $('.modal-overlay');

            $modal.removeClass('modal-in').fadeOut(300);
            $modalOverlay.one('webkitAnimationEnd', function () {
                $(this).hide();
            }).removeClass('modal-overlay-visible').fadeOut(300);
        }
    },
    getWebsiteOfDomainAndPath: function () {
        var url = window.location.href;
        // var url = 'https://s.yuzijiang.tv/web/yzj_app/';

        /**
         * 去除网址中的参数
         */
        var index = 0;

        var index1 = url.indexOf('?');
        var index2 = url.indexOf('#');

        if (index1 != index2) {
            if (index1 === -1) {
                index = index2;
            } else if (index2 === -1) {
                index = index1;
            } else {
                index = (index1 < index2) ? index1 : index2;
            }
        }

        if (index) {
            url = url.substr(0, index);
        }
        /************************************************* */

        /**
         * 去除网址的页面名(对.的检测)
         */
        var urlArr = url.split('/');

        // if (urlArr[urlArr.length - 1].indexOf('.') != -1) {
        //     urlArr.pop();
        // }
        urlArr.pop();
        url = urlArr.join('/') + '/';
        /************************************************* */

        return url;
    },
    convertTimestamp: function (timespamp) {
        var time = timespamp;

        var d = parseInt(time / 1000 / 60 / 60 / 24) //天
        time -= (d * (1000 * 60 * 60 * 24));

        var h = parseInt(time / 1000 / 60 / 60) //时
        time -= (h * (1000 * 60 * 60));

        var m = parseInt(time / 1000 / 60) //分
        time -= (m * (1000 * 60));

        var s = parseInt(time / 1000) //秒
        time -= (s * (1000));

        var resultArr = [];

        if (d > 0) {
            resultArr.push(d + '天');
        }
        if (h > 0) {
            resultArr.push(h + '时');
        }
        if (m > 0) {
            resultArr.push(m + '分');
        }
        if (s > 0) {
            resultArr.push(s + '秒');
        }

        return resultArr.join('');
    },
    /**
     * 把数字形式的参数转化成JSON
     */
    paramsArrayToJson: function (paramsArray) {
        var values = {};
        for (var item in paramsArray) {
            values[paramsArray[item].name] = paramsArray[item].value;
        }

        return values;
    }
};

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};